<template>
  <div>
    <div class="container">
      {{ upload_file || "导入" }}
      <input
        type="file"
        accept=".xls,.xlsx"
        class="upload_file"
        @change="readExcel($event)"
      />
    </div>
  </div>
</template>

<script>
  import XLSX from "xlsx";

  export default {
    data() {
      return {
        upload_file: "",
        lists: [],
      };
    },
    methods: {
      submit_form() {
        // 给后端发送请求，更新数据
          console.log(this.lists);
          this.axios({
              headers: {
                  'Content-Type': 'application/json;charset=UTF-8'
              },
              method: 'post',
              url: 'http://localhost:9090/ViewTable',
              data: JSON.stringify(this.lists),
              //data:this.lists
          }).then(res => {
              console.log(res.data);
              //如果res.data为true（不为null）
              // if(res.data){
              //     console.log("传值成功")
              //     /!* sessionStorage.setItem("userId", res.data.userId);
              //      this.$router.push('/index');*!/
              // }
          })
        console.log("假装给后端发了个请求...");
      },
      readExcel(e) {
        // 读取表格文件
        let that = this;
        const files = e.target.files;
        if (files.length <= 0) {
          return false;
        } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
          this.$message({
            message: "上传格式不正确，请上传xls或者xlsx格式",
            type: "warning"
          });
          return false;
        } else {
          // 更新获取文件名
          that.upload_file = files[0].name;
        }

        const fileReader = new FileReader();
        fileReader.onload = ev => {
          try {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: "binary"
            });
            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容

            //控制台输出表格信息
            console.log(ws);

            var studentData = JSON.stringify(ws);
            sessionStorage.setItem('stuData',studentData);
              // 获取数据的key
              var importDataThead = Array.from(Object.keys(ws[0])).map(
                  item => {
                      return item;
                  }
              );
              that.columnHeader=importDataThead;
              that.checkboxTableColumn=importDataThead.slice(0,9);
              console.log(importDataThead);

              let stuHeaderData = JSON.stringify(importDataThead);
              sessionStorage.setItem('stuHeaderData',stuHeaderData);

              let stuData1 = JSON.stringify(importDataThead,ws,1);
              sessionStorage.setItem('stuData1',stuData1);
              console.log(stuData1);

              that.lists = [];
            // 从解析出来的数据中提取相应的数据
            ws.forEach(item => {
              that.lists.push({
                  studentNumb: item["序号"],
                  studentName: item["学生姓名"],
                  studentSex : item["性别"],
                  studentIDNumb  : item["身份证号"],
                  choiceSchool:item["学校"]
              });
            });
            // 给后端发请求
            this.submit_form();
          } catch (e) {
            return false;
          }
        };
        fileReader.readAsBinaryString(files[0]);
      }
    }
  };
</script>
